/**
 * Copyright (C) 2008 Christopher Allen Ogden
 *
 *     This file is part of Odysi.
 *
 *  Odysi is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Odysi is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Odysi.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <iostream>
#include <boost/filesystem/fstream.hpp>
#include <sstream>
#include <string>
#include <boost/lexical_cast.hpp>
#include "mapFileFormat.h"

using namespace MapFileFormat;
using boost::filesystem::ofstream;
using std::endl;
using std::cout;
using std::string;
using boost::lexical_cast;
using std::exception;
using std::cerr;

namespace {

    void createMap(const string &fileName, unsigned int widthBlocks, unsigned int heightBlocks, unsigned short filler)
    {
        ofstream file(fileName.c_str());

        Header header = {widthBlocks, heightBlocks};
        file.write(reinterpret_cast<char *>(&header), sizeof(Header));

        for (int i = 0; i < widthBlocks * heightBlocks; i++) {
            for (int j = 0; j < 2; j++) {
                for (int k = 0; k < 64; k++) {
                    if (j == 0)
                        file.write(reinterpret_cast<char *>(&filler), sizeof(unsigned short));
                    else {
                        unsigned short zero = 0;
                        file.write(reinterpret_cast<char *>(&zero), sizeof(unsigned short));
                    }
                }
            }
        }

        unsigned int numBlocks = heightBlocks * widthBlocks;
        unsigned int lastHeaderPos = numBlocks * sizeof(Block) + sizeof(Header) + numBlocks * sizeof(ObjectsHeader);
        for (int i = 0; i < numBlocks; i++) {
            ObjectsHeader head = {0, lastHeaderPos};
            file.write(reinterpret_cast<char *>(&head), sizeof(ObjectsHeader));
        }
    }

}

/**
 * The main entry point for the program.
 *
 * @param argc  The number of arguments.
 * @param argv  The arguments.
 * @return      0 on success, 1 on failure.
 */
int main(int argc, char **argv)
{
    try
    {
        // Make sure the correct number of arguments were passed.
        if(argc != 5)
        {
            cout << "Usage: " << argv[0] << " filename width height fill" << endl;
            return 1;
        }

        createMap(argv[1], lexical_cast<unsigned int>(argv[2]), lexical_cast<unsigned int>(argv[3]), lexical_cast<unsigned short>(argv[4]));

        cout << "Finished!" << endl;
    }
    catch (exception &e)
    {
        cerr << "Error: " << e.what() << endl;
    }

    return 0;
}
